package com.company.beauty.common.handler;

import com.company.beauty.common.utils.HttpMessageResultUtil;
import com.company.nuwa.common.constants.Headers;
import com.company.nuwa.common.domain.HttpMessageResult;
import com.company.nuwa.common.utils.RequestContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * <p>Http Message Result 返回补充Header信息</p>
 *
 * @author youyoukele
 * @version 1.0: HttpMessageResultHandler.java
 * @date 2023/11/8 10:02
 */
@Slf4j
@Component
@Aspect
public class HttpMessageResultHandler {

    @Pointcut("execution(* com.company..controller..*(..))")
    private void controller() {
    }

    @Pointcut("execution(* com.company..facade..*(..))")
    private void facade() {
    }

    /**
     * 针对所有的controller都需要新增header返回
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around(value = "controller()")
    public Object handleController(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        return wrapper(proceed);
    }

    /**
     * 针对对外暴露的facade新增header返回
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around(value = "facade()")
    public Object handleFacade(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        // 非终端请求不做处理
        if (!isTerminal()) {
            return proceed;
        }
        return wrapper(proceed);
    }

    /**
     * 包装返回补充header
     *
     * @param proceed
     * @return
     */
    private Object wrapper(Object proceed) {
        if (proceed instanceof HttpMessageResult result) {
            return result.setHeader(HttpMessageResultUtil.getHeader());
        }
        return proceed;
    }

    /**
     * 该请求是否来自终端
     *
     * @return
     */
    private boolean isTerminal() {
        String isTerminal = RequestContextUtil.getHeader(Headers.IS_TERMINAL);
        return Objects.equals(isTerminal, Headers.Value.TERMINAL_FLAG);
    }

}